<!DOCTYPE HTML>
<html>
<head>
<title>Ethiopia Family Medecine Assessment</title>
<script type="text/javascript" charset="utf-8" src="phonegap.0.9.5.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.0a4.min.css" />
<script src="jquery-1.5.min.js"></script>
<script src="jquery.query-2.1.7.js"></script>
<script src="ethiopia.js"></script>
<script src="persistence.js" type="application/javascript"></script>
<script src="persistence.store.sql.js" type="application/javascript"></script>
<script src="persistence.store.websql.js" type="application/javascript"></script>
<script src="jquery.mobile-1.0a4.min.js"></script>
<script src="jquery.easytimepicker.js" type="application/javascript"></script>
<script src="jquery.easytimepicker.mobile.js" type="application/javascript"></script>
<!-- <script src="jquery.easytimepicker.combined.js" type="application/javascript"></script> -->
<link rel="stylesheet" href="ethiopia.css" />
</head>

<body>

<div data-role="page">

	<div data-role="header" data-theme="b" zdata-position="fixed">
		<h1>End of Day Form</h1>
		<a href="endofday.html" class='ui-btn-left ui-btn-back' data-icon='arrow-l' rel="external">Back</a>
		<div data-inline="true" class="ui-btn-right">
			<a  id="newclinical" data-role="button" data-icon="plus" >New clinical</a>
			<a id="newnonclinical" data-role="button" data-icon="plus" >New non clinical</a>
		</div>
		<p id="formIdPlacer" class="activity-head"></p>
	</div><!-- /header -->
<!--	<div id="message" class="ui-body ui-body-e"></div>-->
	<div data-role="content" data-theme="b" id="activityview">
		<ul data-role="listview">
				<li data-role="list-divider">Physician Info</li>
				<!--
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a"><h1>Date</h1></div>
			         	<div class="ui-block-b"><input name="day-date" id="day-date" type="date"></input></div>
				    </fieldset>
				</li>
				-->
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a"><h1>Physician ID</h1></div>
			         	<div class="ui-block-b"><input name="physicianid-textarea" id="physicianid-textarea" type="number"></input></div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-type="horizontal" data-role="fieldcontain">
						<div class="ui-block-a" data-inline="true">
							<h1>How did having an observer change your activity in the workday?</h1>
							<div class="ui-block-a" data-role="controlgroup" id="content-observerchange" ></div>
						</div>
					</fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-type="horizontal" data-role="fieldcontain">
						<div class="ui-block-a" data-inline="true">
							<h1>Please estimate what percentage of your time today was spent in clinical activity?</h1>
							<div class="ui-block-a" data-role="controlgroup" id="content-clinicalestimate" >
						</div>
						</div>
					</fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-type="horizontal" data-role="fieldcontain">
						<div class="ui-block-a" data-inline="true">
							<h1>How closely did today reflect a typical workday for you?</h1>
							<div class="ui-block-a" data-role="controlgroup" id="content-typicalworkday" ></div>
						</div>
						<div class="ui-block-a" data-inline="true">
							<h1>If not typical (1-2), please explain:</h1>
							<div data-role="fieldcontain">
								<textarea cols="35" rows="8" name="typicalworkdaytxt-textarea" id="typicalworkdaytxt-textarea"></textarea>
							</div>
						</div>
					</fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain">
						<div class="ui-block-a"><h1>What clinical or nonclinical problems do you find most challenging in your work?</h1></div>
			         	 <div data-role="fieldcontain">
							<textarea cols="35" rows="8" name="challenges-textarea" id="challenges-textarea"></textarea>
						</div>
				    </fieldset>
				</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain">
						<div class="ui-block-a"><h1>What additional skills, knowledge and/or training would be useful for someone in your position? (Probe only if no answer: "Clinical, non-clinical, manager/leadership roles, computer skills")</h1></div>
			         	 <div data-role="fieldcontain">
							<textarea cols="35" rows="8" name="additionalskills-textarea" id="additionalskills-textarea"></textarea>
						</div>
				    </fieldset>
				</li>
				<li data-role="list-divider">COMPLETE</li>
				<li data-role="fieldcontain" >
					<fieldset data-role="controlgroup"  data-type="horizontal" data-role="fieldcontain" class="ui-grid-a" >
						<div class="ui-block-a"><h1>Complete ?</h1></div>
						<div class="ui-block-b">
				         	<input type="radio" name="complete" id="complete-true" value="yes" />
				         	<label for="complete-true" >Yes</label>
				         	<input type="radio" name="complete" id="complete-false" value="no"  />
				         	<label for="complete-false">No</label>
			         	 </div>
				    </fieldset>
				</li>
				<li id="complete-light"></li>
		</ul>
	</div>
</div>
</body>


<script>
initApp(renderFormView);

var selectSingleOnly = ["typicalworkday","observerchange","clinicalestimate"];

function updateAndBindBoolField(entity,field){
	var val = persistence.get(entity, field);
	$("#"+field+"-"+val).attr('checked', true).checkboxradio("refresh");
	$("#"+field+"-"+!val).attr('checked', false).checkboxradio("refresh");

	$("#"+field+"-"+true).bind("change",function(){
		persistence.set(entity, $(this).attr("name"), true);
		persistence.flush();
		if(field=="complete"){
			updateActivityHead();
		}
	});
	$("#"+field+"-"+false).bind("change",function(){
		persistence.set(entity, $(this).attr("name"), false);
		persistence.flush();
		if(field=="complete"){
			updateActivityHead();
		}
	});
}

function updateAndBindTextField(entity,field){
	var val = persistence.get(entity, field);
	$("#"+field+"-textarea").val(val);

	$("#"+field+"-textarea").bind("focusout",function(){
		console.log($(this).val());
		persistence.set(entity, field, $(this).val());
		persistence.flush();
	});
}

function updateAndBindIntField(entity,field){
	var val = persistence.get(entity, field);

	$("#"+field+"-int").val(val);

	$("#"+field+"-int").bind("focusout",function(){
		console.log($(this).val());
		persistence.set(entity, field, $(this).val());
		persistence.flush();
	});
}

function updateAndBindDateField(entity,field){
	var val = persistence.get(entity, field);

	$("#"+field+"-date").val(val);

	$("#"+field+"-date").bind("focusout",function(){
		console.log($(this).val());
		persistence.set(entity, field, $(this).val());
		persistence.flush();
	});
}

function renderOption(entityNameLC,propid,propval,propremoved){
	var strRemove = "";
	if(propremoved){
		strRemove="(DISABLED) ";
	}
	var str = '<p id="choosen-'+propid+'">'+ strRemove + propval + '</p>';
	$("#placer-select-choice-"+entityNameLC).append(str);
}

function renderSelectView(entityName,entityNameLC,colsLive,callback){
		$("#placer-select-choice-"+entityNameLC).empty();
		$("#select-choice-"+entityNameLC+" option").each(function () {
	   	   if($(this).attr("selected")){
	    	   var propforlistid=$(this).attr("value");
	    	   var propval = $(this).text();
	    	   PropForList.load(propforlistid,function(propforlist){
					var entity = eval("new "+entityName+"({num:0});");
					persistence.add(entity);
					entity.propforlist=propforlist;
					colsLive.add(entity);
					persistence.flush(function(){
						renderOption(entityNameLC,propforlistid,propval,propforlist.removed);
					});
	    	   });
	   	   }

		});
		if (callback) callback();

}

function buildColName(entityNameLC){
	var colname=entityNameLC;
	if(colname.charAt(colname.length-1)!='s'){
		colname+='s';
	}
	return colname;
}

function buildEntityNameLC(entityName){
	var entityNameLC = entityName.toLowerCase();
	return entityNameLC;
}

function renderSelect(entityName,attachLive,callback){
	var entityNameLC = buildEntityNameLC(entityName);
	var selectId='select-choice-'+entityNameLC;
	var multipleStr;
	
	if (jQuery.inArray(entityNameLC, selectSingleOnly) < 0){ multipleStr = 'multiple="multiple"'; }
	
	//for ex, get referredreason only list
	PropForList.all().filter("kind", "=" , entityNameLC).order("value").list(function(propForLists){
		$('#content-'+entityNameLC).empty();
		var str = '<select  data-role="none" name="'+selectId+'" id="'+selectId+'" ' +multipleStr+ ' data-native-menu="'+datanativemenu+'"></select>'
		$('#content-'+entityNameLC).append(str);
		$('#'+selectId).append( '<option value="null" disabled="disabled">Choose...</option>');
		for(var i =0;i<propForLists.length;i++){
			propforlist = propForLists[i];
			if(!propforlist.removed){
				$('#'+selectId).append( '<option id="'+propforlist.id+'" value="'+propforlist.id+'">'+propforlist.value+'</option>');
			}
		}

		//retrieveing colname (should be with a s at the ends.. but not for diagnosis)
		var colname=buildColName(entityNameLC);

		var cols = persistence.get(form,colname);
		cols.list(function(dbPropForLists){
			for(var i =0;i<dbPropForLists.length;i++){
				var res = dbPropForLists[i];
				var propforlist = res.propforlist;
				var propval = propforlist.value;
				renderOption(entityNameLC,propforlist.id,propval,propforlist.removed);
				$('#'+propforlist.id).attr("selected","selected");
				//refresh dyn options...

			}
			//$('#'+selectId).selectmenu('refresh', true);
			//$('#select-choice-'+entityNameLC).page();

			$('#content-'+entityNameLC).page();
			//$('#'+selectId).page();
			//$('#'+selectId).selectmenu('refresh', true);

			if(attachLive){
				var colsLive = cols;
				setSelLiveOnChange(selectId,entityName,entityNameLC,colsLive,function(){});
			}

			if (callback) callback();
		});
	});
}

function setSelLiveOnChange(selectId,entityName,entityNameLC,colsLive,callback){
	$('#'+selectId).live("change",function () {
		 // we destroy all the references on any change on the list
		 colsLive.destroyAll(function(){
			 renderSelectView(entityName,entityNameLC,colsLive,callback);
		 });
	  });
}

function renderActivityContentView() {
	showDefaultMessage();
	//Binding activity core data
	updateAndBindBoolField(form,"complete");

	// automatically retrieve fields of clinical and binding them to the UI checkboxes
	var fields = persistence.getEntityMeta().EndOfDayForm.fields;
	for(var field in fields) {
        var fieldType = fields[field];
        // BOOL fields only
        if(fieldType=="BOOL"){
        	updateAndBindBoolField(form,field);
        }
        else if(fieldType=="TEXT"){
        	updateAndBindTextField(form,field);
        }
        else if(fieldType=="INT"){
	        updateAndBindIntField(form,field);
        }
/*        else if(fieldType=="DATE"){
        	updateAndBindDateField(form,field);
        } */
     }

	// entities For Select to update
	var entitiesFS=["TypicalWorkday", "ObserverChange","ClinicalEstimate"];
	for(var e=0;e<entitiesFS.length;e++) {
		var entityName = entitiesFS[e];
		renderSelect(entityName,true,function(){});
		renderFormAddView(entityName,function(){});
		renderEditDelView(entityName,function(){});
	}

//	renderDateView();	// Date View not used for endofday form
	updateActivityHead();
	hideMessage();
}

function buildCompletionLight(){
	var completeStr = '<span class="ui-icon-complete-' + form.complete;
	if(!form.complete) {
		completeStr += '">incomplete</span>';
	}else{
		completeStr += '">_complete_</span>';
	}
	return completeStr;
}

function updateActivityHead(){
	$("#formIdPlacer").text("EndOfDay #"+form.num +" / "+formatDate(form.day)).append(" / "+buildCompletionLight());
	$("#complete-light").empty();
	$("#complete-light").append(buildCompletionLight());
}

var formId;
var form;
var datanativemenu;

function renderFormView(){
	if (typeof device  != "undefined"){
		document.addEventListener("backbutton", function(){goToPage("endofday.html");}, false);
	}
	formId = $.query.get('act');
	var datanativemenu=true;
	EndOfDayForm.all().filter("id", '=', formId).one(function(result){
		form = result;
		persistence.add(form);
		renderActivityContentView();
	});
}

$('#newclinical').bind('click',function() {
	newClinical(function(activity){
		var str = "activity.html?act=" + activity.id;
		window.location.href = str;
	});
});

$('#newnonclinical').bind('click',function() {
	newNonClinical(function(activity){
		var str = "ncactivity.html?act=" + activity.id;
		window.location.href = str;
	});
});

function renderEditDelUl(entityNameLC) {
	var contentId =entityNameLC+'-editdel-content';
	PropForList.all().filter("kind", "=" , entityNameLC).order("value").list(function(dbPropForLists){
		$('#'+contentId).empty();
		var str ='<ul data-role="listview" data-inset="true" id="'+contentId+'-ul">';
		str +='<li data-role="list-divider">Edit or delete from list:</li>';
		for(var i =0;i<dbPropForLists.length;i++){
			var propforlist = dbPropForLists[i];
			var formId = entityNameLC+'-form-editdel-'+propforlist.id;
			if(!propforlist.removed){
				str +='<li data-role="fieldcontain" >';
				str +='<form id="'+formId+'" action="javascript:;" >';
				str +='<fieldset data-role="fieldcontain" data-inline="true"  data-type="horizontal" >';
				str +='<a id="del-'+propforlist.id+'" data-role="button" data-icon="delete" data-iconpos="notext">del</a>';
				str +='&nbsp;<input data-inline="true" type="text" name="'+entityNameLC+'-input-edit-'+propforlist.id+'" id="'+entityNameLC+'-input-edit-'+propforlist.id+'" value="'+propforlist.value+'" />';
				str +='&nbsp;<input data-role="button" data-icon="check" data-iconpos="notext" type="submit" name="'+entityNameLC+'-submit-edit-'+propforlist.id+'" id="symptom-submit-edit-'+propforlist.id+'" />';
				str +='</fieldset>';
				str +='</form>'
				str +='</li>';
				var inputTextId=entityNameLC+'-input-edit-'+propforlist.id;
				setFormDelEditLive(entityNameLC,contentId,formId,propforlist.id,inputTextId);
			}
		}
		str +='</ul>';
		$('#'+contentId).append(str);
		$('#'+contentId+'-ul').page();
	});
}

function setBindEditDel(entityNameLC){
	var contentId =entityNameLC+'-editdel-content';
	$("#"+contentId).hide();
	$('#'+entityNameLC+'-editdel').bind('click',function() {
		$("#"+contentId).toggle();
		renderEditDelUl(entityNameLC);
	});
}

function setFormDelEditLive(entityNameLC,contentId,formId,propForListId,inputTextId){
	$('#'+formId).die("submit");
	$('#'+formId).live("submit",function(){
		PropForList.all().filter("id","=",propForListId).one(function(propForList){
			persistence.add(propForList);
			propForList.value=$('#'+inputTextId).attr("value");
			persistence.flush(function(){
				$("#"+contentId).hide();
				$('#'+contentId).empty();
				$('#'+propForListId).text(propForList.value);
				$('#choosen-'+propForListId).text(propForList.value);
			});
		});
	});

	$('#del-'+propForListId).die("click");
	$('#del-'+propForListId).live("click",function(){
		if(confirm("This will disable this " + entityNameLC + " from the select box, are you sure ?")){
			PropForList.all().filter("id","=",propForListId).one(function(propForList){
				persistence.add(propForList);
				propForList.removed=true;
				persistence.flush(function(){
					$("#"+contentId).hide();
					$('#'+contentId).empty();
					$('#'+propForListId).remove();
					var strToApp = $('#choosen-'+propForListId).text();
					$('#choosen-'+propForListId).text('(DISABLED) '+strToApp);
				});
			});
		}
	});

}

function renderEditDelView(entityName,callback){

	var entityNameLC = buildEntityNameLC(entityName);

	setBindEditDel(entityNameLC);


	if (callback) callback();
}

function setBindFormToggle(entityNameLC){
	$('#'+entityNameLC+'-add').bind('click',function() {
		$('#'+entityNameLC+'-form-add').toggle();
	});
}

function renderFormAddView(entityName,callback){
	var entityNameLC = buildEntityNameLC(entityName);
	var formId= entityNameLC+'-form-add';

	$('#'+formId).hide();

	setBindFormToggle(entityNameLC);

	setFormAddLive(formId,entityName,entityNameLC);

	if (callback) callback();
}


function setFormAddLive(formId,entityName,entityNameLC){

	$('#'+formId).submit(function(){
		$("#placer-select-choice-"+entityNameLC).empty();
		var inputValue = $('#'+entityNameLC+'-input-add').attr("value").toLowerCase();
		var propForList = newPropForList(entityNameLC,inputValue);
		PropForList.all().filter("devuid", '=', propForList.devuid).filter("kind", '=', propForList.kind).filter("value", '=', propForList.value).one(function(prop){
			// If item exists already than do an update, otherwise it must be added
			if(prop){
				persistence.set(prop, "removed", 0);
				console.log('properly re-enabled');
			}
			else {
			 	persistence.add(propForList);
			}

			persistence.flush(function(){
				PropForList.all().filter("value","=",inputValue).one(function(propForList){
					$('#'+formId).hide();
					var colname = buildColName(entityNameLC);
					var cols = persistence.get(form,colname);
					cols.filter("propforlist","=",propForList.id).one(function(ent){
						var entity =ent;
						if(!entity){
							entity = eval("new "+entityName+"({num:0});");
						}
						persistence.add(entity);
	
						entity.propforlist=propForList;
						cols.add(entity);
						persistence.flush(function(){
							renderSelect(entityName,false,function(){
								$('#'+entityNameLC+'-input-add').attr("value","");
								$('#'+entityNameLC+'-add').focus();
							});
						});
					});
				});
			});
			return false;
		});		
	});
}

/* // Date View not used for endofday form

function renderDateView(){

	$("#date-time-li").append(" " + form.day.toDateString());

	$("#start-period-btn").bind('click',function() {
		showDefaultMessage();
		renderStartInputTime();
		hideMessage();
	});

	$("#end-period-btn").bind('click',function() {
		showDefaultMessage();
		renderEndInputTime();
		hideMessage();
	});

	$("#to-now").live('click',function() {
		showDefaultMessage();
		if( (!$("#start-period").val()) ){
			renderStartInputTime();
		}
		if( (!$("#end-period").val()) ){
			renderEndInputTime();
		}
		var now = new Date();
		var timeStr = formatTime(now);
		$("#start-period").val(timeStr);
		$("#end-period").val(timeStr);
		hideMessage();
	});

	$("#submit-add-period").live('click',function() {
		var currActDate = form.day;
		var currActDateMilli = currActDate.getTime();

	});

	updatePeriodMinMax(renderPeriodView());
}

function updatePeriodMinMax(callback){
	// retrieving min date for activity
	activity.periods.order('start',true).limit(1).one(function(periodStartMin){
		if(periodStartMin!=null){
			activity.veryfirsttime = periodStartMin.start;
		}else{
			activity.veryfirsttime = activity.creationdate;
		}
		// retrieving max date for activity
		activity.periods.order('end',false).limit(1).one(function(periodEndMax){
			if(periodEndMax!=null){
				activity.veryendtime = periodEndMax.end;
			}else{
				activity.veryendtime = null;
			}
			persistence.flush(function(){
				if (callback) callback();
			});
		});
	});
}


function setLivePeriodDel(periodId){
	$('#del-'+periodId).die("click");
	$('#del-'+periodId).live("click",function(){
		form.periods.filter("id","=",periodId).one(function(period){
			form.periods.remove(period);
			persistence.remove(period);
			persistence.flush(function(){
				updatePeriodMinMax(renderPeriodView());
			});
		});
	});
}

function renderPeriodView(){
	form.periods.order('start',false).list(function(periods){
		var str ='<div id="periods-content-ul">';
		str +='<ul data-role="listview" data-inset="true" data-role="fieldcontain">';
		for(var i=0;i<periods.length;i++){
			var period = periods[i];
			var periodEndStr = '__:__';
			if(period.end){
				periodEndStr = formatTime(period.end);
			}
			str +='<li>';
			str +='<div class="ui-grid-b">';
			str +='<div class="ui-block-a"><a data-role="button" data-icon="delete" data-iconpos="notext" id="del-'+period.id+'">del</a></div>';
			str +='<div class="ui-block-b"><h2>'+formatTime(period.start)+' - '+periodEndStr+'</h2></div>';
			str +='</div>';
			str +='</li>';

			setLivePeriodDel(period.id);

		}
		str +='</ul>';
		str +='</div>';

		$("#"+"periods-content").empty();
		if(periods.length==0){
			str = '<p class="activity-selections">No periods for this activity, please choose...</p>';
		}
		$("#"+"periods-content").append(str);
		$("#"+"periods-content-ul").page();
	});
}
*/

</script>
</html>